﻿/*
*┌────────────────────────────────────────────────┐
*│　描    述：DealHttpDataBusiness                                                   
*│　作    者： (Jxw)                                             
*│　版    本：1.0     
*│　功能描述：                                          
*│　创建时间：2021/4/22 16:06:43                        
*└────────────────────────────────────────────────┘
*/

using Data;
using Model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Utility;

namespace Business
{
    public class DealHttpDataBusiness
    {
        private HttpListenerRequest request;
        private HttpListenerResponse response;

        public DealHttpDataBusiness(HttpListenerRequest request, HttpListenerResponse response)
        {
            this.request = request;
            this.response = response;
        }


        /// <summary>
        /// 处理请求数据
        /// </summary>
        public void DealRequestData()
        {
            Stream body = request.InputStream;
            StreamReader reader = null;
            string str = "";
            RetDTO ret = new RetDTO();//返回信息
            ret.ack = new RetCode();
            //MsgInfo Msgback = new MsgInfo();//返回信息
            try
            {
                reader = new StreamReader(body, Encoding.UTF8);
                str = reader.ReadToEnd();//请求的参数
                if (str.Trim() != "")
                {
                    
                    string type = request.Url.Segments[1];//获取地址后面的参数
                    switch (type)
                    {
                        case "pushHospResuorceData"://院内急救资源数据
                            EventUtility.OnShowMsg("收到院内急救资源数据请求", false);
                            if (!string.IsNullOrWhiteSpace(str))
                            {
                                EmergencyHospDTO hospDTO = JsonHelper.DeserializeObject<EmergencyHospDTO>(str);
                                if (hospDTO.resourceEmergencyHosp == null)
                                {
                                    EventUtility.OnShowMsg("院内急救资源数据请求失败，请查看日志", true);
                                    //LogUtility.Error("pushHospResuorceData", JsonHelper.SerializeObject(hospDTO));
                                    ret.ack.code = "-1";
                                    ret.ack.text = "数据为空";
                                    ret.creationTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                    ret.msgId = Guid.NewGuid().ToString();
                                    ret.targetMsgId = hospDTO.msgId;
                                }
                                else
                                {
                                    ret = DapperData.EmergencyHospData(hospDTO.resourceEmergencyHosp, hospDTO.msgId);
                                }

                            }
                            SendMsgBack(ret, response);
                            break;
                        case "pushPatientPreResultData"://救治医院患者数据
                            EventUtility.OnShowMsg("收到救治医院患者数据请求", false);
                            if (!string.IsNullOrWhiteSpace(str))
                            {
                                PushPatientPreDTO patientPre = JsonHelper.DeserializeObject<PushPatientPreDTO>(str);
                                if (patientPre.patientInfoED == null|| patientPre.patientInfoAD==null)
                                {
                                    EventUtility.OnShowMsg("救治医院患者数据请求失败，请查看日志", true);
                                    if (patientPre.patientInfoED==null)
                                    {
                                        ret.ack.text = "急诊患者信息数据为空";
                                    }
                                    if (patientPre.patientInfoAD == null)
                                    {
                                        ret.ack.text = "住院患者信息数据为空";
                                    }
                                    ret.ack.code = "-1";
                                    ret.creationTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                    ret.msgId = Guid.NewGuid().ToString();
                                    ret.targetMsgId = patientPre.msgId;
                                }
                                else
                                {
                                    ret = DapperData.PatientPreData(patientPre);
                                }

                            }
                            SendMsgBack(ret, response);
                            break;
                        case "pushCallDate"://120呼救数据
                            EventUtility.OnShowMsg("收到120呼救数据请求", false);
                            if (!string.IsNullOrWhiteSpace(str))
                            {
                                CommuPatientInfoDTO commuPatientInfoDTO = JsonHelper.DeserializeObject<CommuPatientInfoDTO>(str);
                                if (commuPatientInfoDTO.commuPatientInfo == null)
                                {
                                    EventUtility.OnShowMsg("120呼救数据请求失败，请查看日志", true);
                                    ret.ack.code = "-1";
                                    ret.creationTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                    ret.msgId = Guid.NewGuid().ToString();
                                    ret.targetMsgId = commuPatientInfoDTO.msgId;
                                }
                                else
                                {
                                    //判断是否是多次点击呼叫120
                                    string key = commuPatientInfoDTO.commuPatientInfo.jgdm + commuPatientInfoDTO.commuPatientInfo.mzh;//主键
                                    bool  result=DapperData.ExistCommuPatientInfo(key);
                                    if (result)
                                    {
                                        ret=DapperData.UpdateCommuPatientInfoData(commuPatientInfoDTO);
                                    }
                                    else { 
                                        ret = DapperData.CommuPatientInfoData(commuPatientInfoDTO);
                                    }
                                }

                            }
                            SendMsgBack(ret, response);
                            break;
                        case "queryDeviceBindingRelation"://查询设备绑定关系服务
                            EventUtility.OnShowMsg("收到查询设备绑定关系服务请求", false);
                            //Dictionary<string, string> dic = Utils.Base64ToImage(sjosn, "ssss111");
                            if (!string.IsNullOrWhiteSpace(str))
                            {
                                DeviceBindInfoDTO dto = JsonHelper.DeserializeObject<DeviceBindInfoDTO>(str);
                                var json=DeviceBindBusiness.DataBusiness.GetDeviceBindingRelation(dto.deviceCode,dto.deviceType);
                                SendMsgBack(json, response);
                            }
                            break;
                        case "pushEcgState"://触发查询心电（除颤仪）服务
                            EventUtility.OnShowMsg("收到触发查询心电（除颤仪）服务请求", false);
                            if (!string.IsNullOrWhiteSpace(str))
                            {
                                EcgState ecgState = JsonHelper.DeserializeObject<EcgState>(str);
                                if (ecgState == null)
                                {
                                    EventUtility.OnShowMsg("触发查询心电（除颤仪）服务请求失败，请查看日志", true);
                                    ret.ack.code = "-1";
                                    ret.creationTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                    ret.msgId = Guid.NewGuid().ToString();
                                    ret.targetMsgId = ecgState.msgId;
                                }
                                else
                                {
                                    EventUtility.OnShowMsg("设备编码为："+ ecgState.yqpbch, false);
                                    LogUtility.Debug("pushEcgState", "设备编码为:" + ecgState.yqpbch);
                                    string deviceName = DapperData.EcgStateData(ecgState);//获取设备名称
                                    if (string.IsNullOrEmpty(deviceName))
                                    {
                                        EventUtility.OnShowMsg("未找到设备，请查看日志", true);
                                        ret.ack.code = "-1";
                                        ret.creationTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                        ret.msgId = Guid.NewGuid().ToString();
                                        ret.targetMsgId = ecgState.msgId;
                                        ret.ack.text = "未找到设备: 设备编码为：" + ecgState.yqpbch;
                                        SendMsgBack(ret, response);
                                    }
                                    else {
                                        string data = PatientResuorce.patientResuorce.QueryEcgData(ecgState.yqpbch);
                                        LogUtility.Debug("pushEcgState", data);
                                        if (string.IsNullOrEmpty(data))
                                        {
                                            ret.ack.code = "-1";
                                            ret.creationTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                            ret.msgId = Guid.NewGuid().ToString();
                                            ret.targetMsgId = ecgState.msgId;
                                            ret.ack.text = "未找到任务编码：" + ecgState.yqpbch;
                                            SendMsgBack(ret, response);
                                        }
                                        else {
                                            if (deviceName.Equals("极致"))
                                            {
                                                string jzResult = HttpService.PostResponse(AppConfig.JZQueryUrl, data, AppConfig.appCode, AppConfig.JZsign);

                                                #region 转发心电数据给高迪恩

                                                try
                                                {
                                                    //转发心电数据给高迪恩
                                                    string url = AppConfig.GDNUrl + "?" + "type=jizhi";
                                                    string gdnResult = HttpService.PostResponse(url, jzResult, AppConfig.appCode, AppConfig.GDNsign);
                                                    GDNRetCode gdnRet = JsonHelper.DeserializeObject<GDNRetCode>(gdnResult);
                                                    if (gdnRet.code == 200)
                                                    {
                                                        EventUtility.OnShowMsg("转发极致心电给高迪恩成功", false);
                                                    }
                                                    else
                                                    {
                                                        EventUtility.OnShowMsg("转发极致心电给高迪恩失败！", true);
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    LogUtility.Error("pushEcgState", ex.ToString());
                                                }

                                                #endregion

                                                ret = JsonHelper.DeserializeObject<RetDTO>(jzResult);
                                                List<ResItem> res = JsonHelper.ConvertObjectByJson<List<ResItem>>(ret.ack.res);
                                                if (res.Count > 0)
                                                {
                                                    List<Ecg> ecg = res.FirstOrDefault().ecg;
                                                    ecg.ForEach(q =>
                                                    {
                                                        q.missionId = res.FirstOrDefault().missionId;
                                                        q.padCode = res.FirstOrDefault().padCode;
                                                    });
                                                    ret = DapperData.EcgData(ecg, ret.msgId);
                                                    
                                                    
                                                }
                                            }
                                            if (deviceName.Equals("卓尔"))
                                            {
                                                string zeResult = HttpService.PostResponse(AppConfig.ZEQueryUrl, data, AppConfig.appCode, AppConfig.ZEsign);
                                                LogUtility.Debug("pushEcgState", "卓尔心电"+ zeResult);
                                                #region 转发心电数据给高迪恩

                                                try
                                                {
                                                    //转发心电数据给高迪恩
                                                    string url = AppConfig.GDNUrl + "?" + "type=zhuoer";
                                                    string gdnResult = HttpService.PostResponse(url, zeResult, AppConfig.appCode, AppConfig.GDNsign);
                                                    GDNRetCode gdnRet = JsonHelper.DeserializeObject<GDNRetCode>(gdnResult);
                                                    if (gdnRet.code == 200)
                                                    {
                                                        EventUtility.OnShowMsg("转发极致心电给高迪恩成功", false);
                                                    }
                                                    else
                                                    {
                                                        EventUtility.OnShowMsg("转发极致心电给高迪恩失败！", true);
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    LogUtility.Error("pushEcgState", ex.ToString());
                                                }

                                                #endregion


                                                ret = JsonHelper.DeserializeObject<RetDTO>(zeResult);
                                                List<ResItem> res = JsonHelper.ConvertObjectByJson<List<ResItem>>(ret.ack.res);
                                                if (res.Count > 0)
                                                {
                                                    EquipData equipData = res.FirstOrDefault().equipData;
                                                    ret = DapperData.EquipDataInfo(equipData, ret.msgId);
                                                }
                                            }
                                        }
                                       
                                    }
                                }

                            }
                            SendMsgBack(ret, response);
                            break;
                        case "getHospSort"://获取救治医院排序
                            EventUtility.OnShowMsg("收到督导端请求获取救治医院排序", false);
        
                            Hashtable ht = new Hashtable();
                            if (!string.IsNullOrWhiteSpace(str))
                            {
                                HospSort hosp = JsonHelper.DeserializeObject<HospSort>(str);
                                if (hosp== null)
                                {
                                    EventUtility.OnShowMsg("经纬度坐标为空，请查看日志", true);
                                    ret.ack.code = "-1";
                                    ret.ack.text = "经纬度坐标为空";
                                    ret.creationTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                    ret.msgId = Guid.NewGuid().ToString();
                                    ret.targetMsgId = str;
                                }
                                else
                                {
                                    List<hospDTO> hospList = new List<hospDTO>();
                                    hosp.msgId = Guid.NewGuid().ToString();
                                    hosp.creationTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                    hosp.vendorId = "ANKE";
                                    string data = JsonHelper.SerializeObject(hosp);
                                    string json = HttpService.PostResponse(AppConfig.HospSortUrl, data, AppConfig.appCode, AppConfig.HospSortsign);
                                    RetDTO wdRet = JsonHelper.DeserializeObject<RetDTO>(json);
                                    if (wdRet.ack.res != null)
                                    {
                                        hospList = wdRet.ack.res.FirstOrDefault()?.hospList;
                                        if (hospList != null)
                                        {
                                            EventUtility.OnShowMsg("获取救治医院排序信息成功", false);
                                            ht.Add("code", "0");
                                            ht.Add("message", "获取成功");
                                            ht.Add("data", JsonHelper.SerializeObject(hospList));
                                        }
                                        else
                                        {
                                            EventUtility.OnShowMsg("获取救治医院排序信息失败", true);
                                            ht.Add("code", "-1");
                                            ht.Add("message", "数据为空");
                                            ht.Add("data", JsonHelper.SerializeObject(hospList));
                                        }

                                    }
                                    else
                                    {
                                        EventUtility.OnShowMsg("获取救治医院排序信息失败", true);
                                        ht.Add("code", "-1");
                                        ht.Add("message", "数据为空");
                                        ht.Add("data", JsonHelper.SerializeObject(hospList));
                                    }

                                    //List<OrgResourceDTO> orgResources = new List<OrgResourceDTO>() { new OrgResourceDTO() {
                                    //        resourceFree="23",
                                    //        resourceType="导管室",
                                    //        remark="测试不合法了啥"
                                    //},new OrgResourceDTO(){
                                    //        resourceFree="23",
                                    //        resourceType="PAD",
                                    //        remark="全流程测试"
                                    //} };
                                    //hospList.Add(new hospDTO()
                                    //{
                                    //    orgCode = "008",
                                    //    orgName = "测试",
                                    //    distance = "15916.422726246648",
                                    //    resources = orgResources
                                    //});
                                    //hospList.Add(new hospDTO()
                                    //{
                                    //    orgCode = "005",
                                    //    orgName = "测试",
                                    //    distance = "20445.117681894826",
                                    //    resources = orgResources
                                    //});
                                    //hospList.Add(new hospDTO()
                                    //{
                                    //    orgCode = "010",
                                    //    orgName = "测试",
                                    //    distance = "26235.68909632512",
                                    //    resources = orgResources
                                    //});
                                    //hospList.Add(new hospDTO()
                                    //{
                                    //    orgCode = "007",
                                    //    orgName = "测试",
                                    //    distance = "22559.692092980127",
                                    //    resources = orgResources
                                    //});

                                    //ht.Add("code", "0");
                                    //ht.Add("message", "空");
                                    //ht.Add("data", JsonHelper.SerializeObject(hospList));
                                }
                            }
                            SendMsgBack(ht, response);
                            break;
                        //case "queryDeviceBindInfo":
                        //    EventUtility.OnShowMsg("收到查询设备绑定信息的请求", false);

                        //    break;
                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                SendMsgBack(ret, response);
                EventUtility.OnShowMsg("处理数据异常,原因:" + ex.Message, true);
                LogUtility.Error("DealRequestData", "处理数据异常,原因:" + ex.Message);
            }
            finally
            {
                body.Close();
                reader.Close();
            }
        }


        /// <summary>
        /// 发送字符串消息
        /// </summary>
        /// <param name="data">回复的字符串</param>
        /// <param name="response"></param>
        public void SendMsgBack(object data, HttpListenerResponse response)
        {
            try
            {
                string jsonData = JsonHelper.SerializeObject(data);
                LogUtility.Debug("SendMsgBack", jsonData);
                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(jsonData);
                response.ContentLength64 = buffer.Length;
                Stream output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                output.Close();
            }
            catch (Exception ex)
            {
                LogUtility.Error("SendMsgBack", data.ToString());
                LogUtility.Error("SendMsgBack:Message", ex.Message);
                EventUtility.OnShowMsg("发送字符串消息失败,原因:" + ex.Message, true);
            }
        }

        #region 委托

        //public event Action<string, bool> ShowMsgEvent;

        //private void OnShowMsg(string Msg, bool IsError)
        //{
        //    Action<string, bool> showAction = new Action<string, bool>((msg, isError) =>
        //    {
        //        if (ShowMsgEvent != null)
        //        {
        //            ShowMsgEvent(msg, isError);
        //        }
        //    });
        //    showAction.Invoke(Msg, IsError);
        //}




        ///// <summary>
        ///// 显示消息委托
        ///// </summary>
        ///// <param name="messageLevel"></param>
        ///// <param name="msg"></param>
        //public delegate void ShowMessageHandler(AnchorEnum.EMessageLevel messageLevel, string message);
        //public event ShowMessageHandler ShowMessage;
        //private void OnShowMessage(AnchorEnum.EMessageLevel messageLevel, string message)
        //{
        //    if (ShowMessage != null)
        //    {
        //        Control target = ShowMessage.Target as Control;
        //        if (target != null && target.InvokeRequired)
        //            target.BeginInvoke(ShowMessage, new object[] { messageLevel, message });
        //        else
        //            ShowMessage(messageLevel, message);
        //    }
        //}

        #endregion

    }

}
